package com.htfyun.factorytest.config;

import com.htfyun.factorytest.RootApplication;
import com.htfyun.factorytest.utils.DebugLog;

import org.ini4j.Wini;

import java.io.File;
import java.io.IOException;

public class Configuration {
    private static Configuration _instance = null;
    private Wini ini = null;
    private static final String CONFIG_INI = RootApplication.getContext().getExternalFilesDir(null).getAbsolutePath() + "/config.ini";

    private Configuration() {
        try {
            File config = new File(CONFIG_INI);
            if (!config.exists()) {
                config.createNewFile();
            }
            ini = new Wini(config);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public synchronized static Configuration getInstance() {
        if (_instance == null) {
            _instance = new Configuration();
        }
        return _instance;
    }

    public String getConfig(String xSectionName, String xFieldValue) {

        String readValue = "";

        if (ini.get(xSectionName, xFieldValue) != null) {
            readValue = ini.get(xSectionName, xFieldValue);
        }

        return readValue;
    }

    public void setConfig(String xSectionName, String xFieldValue, String xValue) {

        DebugLog.e("Section: " + xSectionName
                + " Field:   " + xFieldValue
                + " Value:   " + xValue);

        try {
            ini.put(xSectionName, xFieldValue, xValue);
            ini.store();
        } catch (Exception e) {
            DebugLog.e(xValue + " could not be stored.");
            e.printStackTrace();
        }
    }

    public void removeSection(String xSectionName) {
        try {
            ini.remove(xSectionName);
            ini.store();
        } catch (Exception e) {
            DebugLog.e(xSectionName + " could not be removed.");
            e.printStackTrace();
        }
    }
}
